package com.hamilton.erik.pt.mobile.android;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.android.volley.Response;
import com.hamilton.erik.pt.core.enumeration.EnclosureShape;
import com.hamilton.erik.pt.core.model.Animal;
import com.hamilton.erik.pt.core.model.Enclosure;
import com.hamilton.erik.pt.mobile.android.app.DoublePickerDialog;
import com.hamilton.erik.pt.mobile.android.volley.response.error.listener.DisplayErrorErrorListener;
import com.hamilton.erik.pt.mobile.client.VolleyJsonRestClient;
import com.hamilton.erik.pt.mobile.util.ResultUtil;
import com.hamilton.erik.pt.mobile.util.ServerUtil;

public class EditEnclosureActivity extends EditDataActivity {

	private final int HEIGHT_PICKER_DIALOG_ID = 0;
	private final int LENGTH_PICKER_DIALOG_ID = 1;
	private final int WIDTH_PICKER_DIALOG_ID = 2;
	private final int VOLUME_PICKER_DIALOG_ID = 3;
	
	private Animal animal;
	private Enclosure enclosure;
	private ProgressDialog progressDialog = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_enclosure);
		
		findViewById(R.id.enclosure_edit_height_field).setOnClickListener(
				new OnClickListener() {
					@SuppressWarnings("deprecation")
					@Override
					public void onClick(View view) {
					    showDialog(HEIGHT_PICKER_DIALOG_ID);
					}
				});

		findViewById(R.id.enclosure_edit_length_field).setOnClickListener(
				new OnClickListener() {
					@SuppressWarnings("deprecation")
					@Override
					public void onClick(View view) {
					    showDialog(LENGTH_PICKER_DIALOG_ID);
					}
				});

		findViewById(R.id.enclosure_edit_width_field).setOnClickListener(
				new OnClickListener() {
					@SuppressWarnings("deprecation")
					@Override
					public void onClick(View view) {
					    showDialog(WIDTH_PICKER_DIALOG_ID);
					}
				});

		findViewById(R.id.enclosure_edit_volume_field).setOnClickListener(
				new OnClickListener() {
					@SuppressWarnings("deprecation")
					@Override
					public void onClick(View view) {
					    showDialog(VOLUME_PICKER_DIALOG_ID);
					}
				});

		findViewById(R.id.enclosure_edit_save_edit_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						save();
					}
				});
		
		findViewById(R.id.enclosure_edit_cancel_edit_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						cancel();
					}
				});
		
		animal = (Animal) getIntent().getSerializableExtra(
				getString(R.string.extra_animal_object));

		if (!TextUtils.isEmpty(animal.getName())) {
			setTitle("Editing " + animal.getName() + "'s Enclosure");
		}
		
		enclosure = (Enclosure) getIntent().getSerializableExtra(
					getString(R.string.extra_enclosure_object));

		populateFields();
	}

	protected void populateFields() {
		if (enclosure != null) {
			String temp;

			temp = enclosure.getEnclosureType();
			if (!TextUtils.isEmpty(temp)) {
				EditText typeEditText = (EditText) findViewById(R.id.enclosure_edit_type_field);
				typeEditText.setText(temp);
			}
			
			Spinner shapeDropDown = (Spinner) findViewById(R.id.enclosure_edit_shape_drop_down);
			ArrayAdapter<EnclosureShape> shapeDropDownAdapter =
					new ArrayAdapter<EnclosureShape>(this, android.R.layout.simple_spinner_item, EnclosureShape.values());
			shapeDropDown.setAdapter(shapeDropDownAdapter);
			if (enclosure.getShape() != null) {
				int dropDownPosition = shapeDropDownAdapter.getPosition(enclosure.getShape());
				shapeDropDown.setSelection(dropDownPosition);
			}
			
			if (enclosure.getHeight() != null) {
				EditText heightUnitEditText = (EditText) findViewById(R.id.enclosure_edit_height_field);
				heightUnitEditText.setText(enclosure.getHeight().toString());
			}
			
			if (enclosure.getLength() != null) {
				EditText lengthUnitEditText = (EditText) findViewById(R.id.enclosure_edit_length_field);
				lengthUnitEditText.setText(enclosure.getLength().toString());
			}
			
			if (enclosure.getWidth() != null) {
				EditText widthUnitEditText = (EditText) findViewById(R.id.enclosure_edit_width_field);
				widthUnitEditText.setText(enclosure.getWidth().toString());
			}
			
			if (enclosure.getVolume() != null) {
				EditText volumeUnitEditText = (EditText) findViewById(R.id.enclosure_edit_volume_field);
				volumeUnitEditText.setText(enclosure.getVolume().toString());
			}
			
			temp = enclosure.getVolumeUnit();
			if (!TextUtils.isEmpty(temp)) {
				EditText volumeUnitEditText = (EditText) findViewById(R.id.enclosure_edit_volume_unit_field);
				volumeUnitEditText.setText(temp);
			}
		}
	}
	
	protected boolean validateFields() {
		boolean valid = true;
		View focusView = null;
		
		EditText typeField = ((EditText) findViewById(R.id.enclosure_edit_type_field));
		if (TextUtils.isEmpty(typeField.getText().toString())) {
			typeField.setError(getString(R.string.error_field_required));
			focusView = typeField;
			valid = false;
		}		
		
		if (!valid) {
			focusView.requestFocus();
		}
		
		return valid;
	}
	
	protected void save() {
		
		if(validateFields()) {
			StringBuilder url = new StringBuilder(ServerUtil.getInstance().buildEnclosurePath());
			url.append("/upsert");
			
			Map<String, String> params = new HashMap<String, String>();
			String temp;
			
			if(enclosure.getId() != null) {
				params.put("id", enclosure.getId().toString().trim());
			}
			
			if(enclosure.getAnimalId() != null) {
				params.put("animalId", enclosure.getAnimalId().toString().trim());
			}
			
			temp = ((EditText)findViewById(R.id.enclosure_edit_type_field)).getText().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("enclosureType", temp);
				enclosure.setEnclosureType(temp);
			}
			
			temp = ((Spinner)findViewById(R.id.enclosure_edit_shape_drop_down)).getSelectedItem().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("shape", temp);
				enclosure.setShape(temp);
			}
			
			temp = ((EditText)findViewById(R.id.enclosure_edit_height_field)).getText().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("height", temp);
				enclosure.setHeight(Double.parseDouble(temp));
			}
			
			temp = ((EditText)findViewById(R.id.enclosure_edit_length_field)).getText().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("length", temp);
				enclosure.setLength(Double.parseDouble(temp));				
			}
			
			temp = ((EditText)findViewById(R.id.enclosure_edit_width_field)).getText().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("width", temp);
				enclosure.setWidth(Double.parseDouble(temp));
			}
			
			temp = ((EditText)findViewById(R.id.enclosure_edit_volume_field)).getText().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("volume", temp);
				enclosure.setVolume(Double.parseDouble(temp));
			}
			
			temp = ((EditText)findViewById(R.id.enclosure_edit_volume_unit_field)).getText().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("volumeUnit", temp);
				enclosure.setVolumeUnit(temp);
			}
			
			if (progressDialog == null) {
		        progressDialog = new ProgressDialog(this);
		        progressDialog.setTitle(getString(R.string.progress_uploading_title));
		        progressDialog.setMessage(getString(R.string.edit_enclosure_progress_saving_enclosure));
		    }
		    progressDialog.show();
		    
			VolleyJsonRestClient.getClient()
					.putJsonObject(
							url.toString(),
							new SaveSuccessListener(), 
							new DisplayErrorErrorListener(this, progressDialog),
							params);
		}
	}
	
	protected void cancel() {
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_enclosure, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch(item.getItemId()) {
			case R.id.action_edit_enclosure_save :
				save();
				return true;
			default :
				return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id) {
		
			case HEIGHT_PICKER_DIALOG_ID :
				EditText heightEditText = (EditText) findViewById(R.id.enclosure_edit_height_field);
				double heightValue = 0.0;
				if(!TextUtils.isEmpty(
						heightEditText.getText().toString())) {
						heightValue = Double.parseDouble(heightEditText.getText().toString());
				}
				
				DoublePickerDialog heightDoublePickerDialog =
						new DoublePickerDialog(this, heightDoubleSetListener);
				heightDoublePickerDialog.setMaxValue(10000);
				heightDoublePickerDialog.setMinValue(0);
				heightDoublePickerDialog.setValue(heightValue);
				
				return heightDoublePickerDialog;
				
			case LENGTH_PICKER_DIALOG_ID :
				EditText lengthEditText = (EditText) findViewById(R.id.enclosure_edit_length_field);
				double lengthValue = 0.0;
				if(!TextUtils.isEmpty(
						lengthEditText.getText().toString())) {
						lengthValue = Double.parseDouble(lengthEditText.getText().toString());
				}
				
				DoublePickerDialog lengthDoublePickerDialog =
						new DoublePickerDialog(this, lengthDoubleSetListener);
				lengthDoublePickerDialog.setMaxValue(10000);
				lengthDoublePickerDialog.setMinValue(0);
				lengthDoublePickerDialog.setValue(lengthValue);
				
				return lengthDoublePickerDialog;
				
			case WIDTH_PICKER_DIALOG_ID :
				EditText widthEditText = (EditText) findViewById(R.id.enclosure_edit_width_field);
				double widthValue = 0.0;
				if(!TextUtils.isEmpty(
						widthEditText.getText().toString())) {
						widthValue = Double.parseDouble(widthEditText.getText().toString());
				}
				
				DoublePickerDialog widthDoublePickerDialog =
						new DoublePickerDialog(this, widthDoubleSetListener);
				widthDoublePickerDialog.setMaxValue(10000);
				widthDoublePickerDialog.setMinValue(0);
				widthDoublePickerDialog.setValue(widthValue);
				
				return widthDoublePickerDialog;
				
			case VOLUME_PICKER_DIALOG_ID :
				EditText volumeEditText = (EditText) findViewById(R.id.enclosure_edit_volume_field);
				double volumeValue = 0.0;
				if(!TextUtils.isEmpty(
						volumeEditText.getText().toString())) {
						volumeValue = Double.parseDouble(volumeEditText.getText().toString());
				}
				
				DoublePickerDialog volumeDoublePickerDialog =
						new DoublePickerDialog(this, volumeDoubleSetListener);
				volumeDoublePickerDialog.setMaxValue(1000000);
				volumeDoublePickerDialog.setMinValue(0);
				volumeDoublePickerDialog.setValue(volumeValue);
				
				return volumeDoublePickerDialog;
		}
		
		return null;
	}

	private DoublePickerDialog.OnDoubleSetListener heightDoubleSetListener =
			new DoublePickerDialog.OnDoubleSetListener() {
				
				@Override
				public void onDoubleSet(Double value) {
					EditText heightEditText = 
							(EditText) findViewById(R.id.enclosure_edit_height_field);
					
					heightEditText.setText(value.toString());
				}
			};

	private DoublePickerDialog.OnDoubleSetListener lengthDoubleSetListener =
			new DoublePickerDialog.OnDoubleSetListener() {
				
				@Override
				public void onDoubleSet(Double value) {
					EditText lengthEditText = 
							(EditText) findViewById(R.id.enclosure_edit_length_field);
					
					lengthEditText.setText(value.toString());
				}
			};

	private DoublePickerDialog.OnDoubleSetListener widthDoubleSetListener =
			new DoublePickerDialog.OnDoubleSetListener() {
				
				@Override
				public void onDoubleSet(Double value) {
					EditText widthEditText = 
							(EditText) findViewById(R.id.enclosure_edit_width_field);
					
					widthEditText.setText(value.toString());
				}
			};

	private DoublePickerDialog.OnDoubleSetListener volumeDoubleSetListener =
			new DoublePickerDialog.OnDoubleSetListener() {
				
				@Override
				public void onDoubleSet(Double value) {
					EditText volumeEditText = 
							(EditText) findViewById(R.id.enclosure_edit_volume_field);
					
					volumeEditText.setText(value.toString());
				}
			};
	
	private class SaveSuccessListener implements Response.Listener<JSONObject> {

		@Override
		public void onResponse(JSONObject response) {
			if (progressDialog != null && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			
			Intent result = new Intent();
			result.putExtra(getString(R.string.extra_animal_object), animal);
			result.putExtra(getString(R.string.extra_enclosure_object), enclosure);
			
			setResult(ResultUtil.RESULT_SUCCESS, result);
			finish();
		}
		
	}
}
